package org.iabako.client.ui.form.business.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTMLPanel;
import org.iabako.client.config.page.PageConfigEnum;
import org.iabako.client.navigation.NavigationController;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.ui.form.AbstractForm;
import org.iabako.client.ui.form.business.sale.make.SaleMakeForm;
import org.iabako.client.ui.layout.field.IField;
import org.iabako.client.ui.layout.template.PopupTagItem;
import org.iabako.client.ui.layout.widget.validation.ValidationMessage;
import org.iabako.client.ui.page.business.client.ClientSearch;
import org.iabako.client.user.AuthenticateUserProvider;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.entity.business.Client;
import org.iabako.shared.entity.enumeration.NotificationType;
import org.iabako.shared.entity.enumeration.TrackingType;
import org.iabako.shared.iservice.business.ClientServiceAsync;
import org.iabako.shared.tools.GenericTools;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jose on 11/09/14.
 */
public abstract class ClientForm extends AbstractForm {

    interface MyUiBinder extends UiBinder<HTMLPanel, ClientForm> {
    }

    protected MyUiBinder binderClientForm = GWT.create(MyUiBinder.class);

    protected final ClientServiceAsync clientServiceAsync = ClientServiceAsync.Util.getInstance();

    @UiField
    public ClientInformationForm clientInformationForm;
    @UiField
    public ClientSalesForm clientSalesForm;
    @UiField
    public ClientConversationsForm clientConversationsForm;

    boolean isCreationMode;

    protected ClientForm(PageConfigEnum pageConfigEnum, String explanationMenuLabel, boolean isCreationMode) {

        this.isCreationMode = isCreationMode;

        setForm(binderClientForm, pageConfigEnum, explanationMenuLabel);

        for (final PopupTagItem popupTagItem : popup.popupTagItems.keySet()) {
            switch (popupTagItem.pageTagItemEnum) {
                case ClientInformation:
                    popup.popupTagItems.put(popupTagItem, clientInformationForm);
                    break;
                case ClientPayment:
                    popup.popupTagItems.put(popupTagItem, clientSalesForm);
                    popupTagItem.setAbstractForm(clientSalesForm);
                    break;
                case ClientConversation:
                    popup.popupTagItems.put(popupTagItem, clientConversationsForm);
                    popupTagItem.setAbstractForm(clientConversationsForm);
                    break;
            }
        }

        if (isCreationMode) {
            clientServiceAsync.getNextAvailableId(new IabakoAsyncCallback<String>() {
                public void onSuccess(String result) {
                    clientInformationForm.number.setValue(result);
                    super.onSuccess(result);
                }
            });
        }

        clientInformationForm.setParentForm(this);
        clientSalesForm.setParentForm(this);
        clientConversationsForm.setParentForm(this);

        if (isCreationMode) {
            clientConversationsForm.setVisible(false);
            clientSalesForm.setVisible(false);
            clientInformationForm.initializeCustomFieldsForm();
        }
    }

    public void refreshSales() {
        clientSalesForm.refreshSales();
    }

    public void setClient(Client client) {
        this.entity = client;
        clientInformationForm.setClient(client);

        if (!isCreationMode) {
            clientSalesForm.setClient(client);
            clientConversationsForm.setClient(client);
        }

        enableAddLinkAction(clientServiceAsync);
    }

    @Override
    protected List<IField> getMandatoryFields() {
        return clientInformationForm.getMandatoryFields();
    }

    @Override
    protected AbstractEntity getEntity() {
        return clientInformationForm.getEntity();
    }

    public Client getClient() {
        return (Client) entity;
    }

    private boolean otherValidation() {
        if (clientInformationForm.birthday.getValue() != null &&
                clientInformationForm.birthday.getValue().compareTo(GenericTools.getDateWithoutTime()) > 0) {
            ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "server_validation_birthday_must_be_in_past");
            return false;
        }
        return true;
    }

    @Override
    public boolean validate() {
        if (!uiValidation()) {
            return false;
        }

        if (!otherValidation()) {
            return false;
        }

        Client client = (Client) serverValidation();
        if (client == null) {
            return false;
        }

        final boolean creation = client.getId() == null;

        clientServiceAsync.save(client, client.getCustomFieldValues(), new IabakoAsyncCallback<Client>() {
            public void onSuccess(Client result) {
                popup.handleClickClose();

                ValidationMessage validationMessageInPageContent = ValidationMessage.getFromRootPage();
                if (creation) {

                    if (parentForm != null) {
                        NavigationController.getInstance().goTo(parentForm);

                        ((SaleMakeForm) parentForm).saleMakeClientChoice.clientSuggestSelectionHandler.setEntity(result);
                        ((SaleMakeForm) parentForm).saleMakeClientChoice.clientSuggestSelectionHandler.setText(result.getName());
                        ((SaleMakeForm) parentForm).saleMakeClientChoice.clientSuggestSelectionHandler.setHiddenSelectionCode(result.getId() + "");

                        ((SaleMakeForm) parentForm).messages.showSuccessMessage("validation_client_form_create_success");
                        return;
                    }
                    validationMessageInPageContent.showSuccessMessage("validation_client_form_create_success");
                    AuthenticateUserProvider.getTrackingPanel().refresh(TrackingType.clientNew);
                } else {
                    validationMessageInPageContent.showSuccessMessage("validation_client_form_modify_success");
                    AuthenticateUserProvider.getTrackingPanel().refresh(TrackingType.clientModify);
                }

                if (NavigationController.getInstance().getRootPage().pageContentComposite instanceof ClientSearch) {
                    //If rootPage is ClientSearch, we have to refresh search
                    ((ClientSearch) NavigationController.getInstance().
                            getRootPage().pageContentComposite).clientSearchForm.searchForm.search(false);
                }

                AuthenticateUserProvider.getNotificationPanel().refresh(NotificationType.birthday);

                super.onSuccess(result);
            }
        });
        return true;
    }

}
